package tw.asap.plus.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.GeolocationPermissions;
import android.webkit.SslErrorHandler;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebHistoryItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;


import tw.asap.plus.R;
import tw.asap.plus.common.ConstValue;
import tw.asap.plus.ui.BaseActivity;
import tw.asap.plus.ui.custom.AppBar;
import tw.asap.plus.utils.AppManager;
import tw.asap.plus.utils.Toaster;
import tw.asap.plus.utils.Utils;
import timber.log.Timber;

public class WebActivity extends BaseActivity {

    public static final String TAG = WebActivity.class.getSimpleName();

    private final int REQUEST_LOGIN_CODE = 0x03;

    private WebView webView;
    private String currentUrl;
    private ProgressBar progressBar;

    // 隐藏webview导航栏
    private static final String HIDE_NAV = "javascript:hideNav()";

    //
    private String NEAR_MERCHANT = "near-merchant://";
    // 复制微信号
    private static final String HOST_COPY = "copy";

    private static final String HOST_LOGIN = "login";
    // 获取shopname
    private String HOST_GET_PROFILE = "get_profile";

    private String HOST_FOOD_MANAGE = "food-manage";

    private String HOST_TAKEOUT_MANAGE = "takeout-manage";

    //下拉刷新
    private SwipeRefreshLayout swipeRefreshLayout;
    private int touchCount;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        initTitle();

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setColorSchemeResources(R.color.qtTextPink, R.color.qfpay_blue);

        progressBar = (ProgressBar) findViewById(R.id.progress);
        progressBar.setVisibility(View.GONE);
        webView = (WebView) findViewById(R.id.webView);
        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDefaultTextEncodingName("utf-8");
        //启用地理定位
        settings.setGeolocationEnabled(true);
        //开启DomStorage缓存
        settings.setDomStorageEnabled(true);
        settings.setGeolocationDatabasePath(getFilesDir().getPath());
        //启用数据库
        settings.setDatabaseEnabled(true);
        dealUrl(getIntent());

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //获取历史列表
                WebBackForwardList mWebBackForwardList = webView.copyBackForwardList();
                WebHistoryItem webHistoryItem = mWebBackForwardList.getCurrentItem();
                if (null != webHistoryItem) {
                    String url = webHistoryItem.getUrl();
                    loadWebView(webView, url);
                }
                swipeRefreshLayout.setRefreshing(false);
            }
        });

    }


    private void initTitle() {
        setHasAppBar(true);
        AppBar appBar = getAppBar();
        appBar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (touchCount == 6) {
                    webView.loadUrl(ConstValue.H5_ENVIROMENT_SWITCH_URL);
                    touchCount = 0;
                    return true;
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    touchCount++;
                }

                return true;
            }
        });
        appBar.setLeftNavigation(R.drawable.ic_back, new AppBar.OnLeftClickListener() {
            @Override
            public void onClick(View v) {
                handleBackReturnEvent();
            }
        });
//        appBar.setRightNavigation(R.drawable.ic_settings, new AppBar.OnRightClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(WebActivity.this, SettingActivity.class));
//            }
//        });
    }


    private void dealUrl(Intent intent) {
        currentUrl = intent.getStringExtra("webURL");

//        boolean push = intent.getBooleanExtra("push", false);

        if (TextUtils.isEmpty(currentUrl)) {
            currentUrl = ConstValue.H5_MAIN_WEBURL;
        }

        setCookie();
        setDefaultClient();
        loadWebView(webView, currentUrl);
    }

    /**
     * 设置默认的client
     */
    private void setDefaultClient() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setBuiltInZoomControls(true);

        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);

                if (newProgress >= 80) {
                    progressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                // 改变Title
                getAppBar().setTitle(title);
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
                // 请求定位信息
                final boolean remember = false;
                callback.invoke(origin, true, remember);
            }

            @Override
            public void onGeolocationPermissionsHidePrompt() {
                super.onGeolocationPermissionsHidePrompt();
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {
                    judgeToStart(view, url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }

            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
                Timber.i("onReceiveSslError----" + error.toString());
//                webView.loadUrl(currentUrl);
                super.onReceivedSslError(view, handler, error);
            }

            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                progressBar.setVisibility(View.VISIBLE);
                if (url != null && url.equalsIgnoreCase(ConstValue.H5_MAIN_WEBURL)) {
                    getAppBar().setShowLeft(false);
                } else {
                    getAppBar().setShowLeft(true);
                }
            }

            public void onPageFinished(WebView view, String url) {
                webView.loadUrl(HIDE_NAV);
                progressBar.setVisibility(View.GONE);
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Timber.i("onReceiveError----" + failingUrl);
                progressBar.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 加载url
     */
    private void loadWebView(WebView webView, String url) {
        Timber.i(TAG, "============= load url = " + url);
        webView.loadUrl(url);
    }

    /**
     * 返回键的处理
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            handleBackReturnEvent();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void handleBackReturnEvent() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
    }


    /**
     * 设置Cookie
     */
    private void setCookie() {
        Timber.i("start set cookie...");
        CookieSyncManager.createInstance(WebActivity.this);
        CookieManager cookieManager = CookieManager.getInstance();
        CookieSyncManager.getInstance().startSync();
        webView.clearCache(true);
        webView.clearHistory();

        boolean offlineDev = spUtil.getBoolean(ConstValue.Sp.OFFLINE_DEV, false);
        String sessionCookie = "sessionid = " + spUtil.getString(ConstValue.Sp.SESSIONID, "") + "; domain=.qfpay.com; path =/";
        if (offlineDev) {
            sessionCookie += ";mmfct=1";
        }
        cookieManager.setCookie(".qfpay.com", sessionCookie);
        cookieManager.setCookie(currentUrl, sessionCookie);
        Timber.i("sessioncookie---" + sessionCookie);
    }


    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Timber.e(TAG, "============== onNewIntent()");
        dealUrl(intent);
    }


    /**
     * 复制微信号
     *
     * @param view
     * @param url
     * @throws Exception
     */
    private void judgeToStart(WebView view, final String url) throws Exception {

        if (url.contains(NEAR_MERCHANT)) {
            Uri uri = Uri.parse(url);
            String host = uri.getHost();
            if (host.equals(HOST_COPY)) {  // 复制微信号
                String data = uri.getQueryParameter("data");
                Utils.onCopy2Clipboar(WebActivity.this, data);
                Toaster.l(WebActivity.this, getString(R.string.text_copy_wx));
            } else if (host.equals(HOST_GET_PROFILE)) {  // 获取shopname
                String data = uri.getQueryParameter("data");
                getAppBar().setTitle(data);
            } else if (host.equalsIgnoreCase(HOST_LOGIN)) {
                Toast.makeText(this, "用户异常,请重新登录!", Toast.LENGTH_SHORT).show();
                clearUSerCache();
                Intent intent = new Intent(WebActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        } else {
            if (url.startsWith("tel")) {
                String tellephone = url.replace("tel:", "");
                showNormalDialog("提示", "确定拨打客户电话:" + tellephone + "?", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
                        startActivity(intent);
                    }
                }, null);

                return;
            }
            currentUrl = url;
            loadWebView(view, url);
        }

    }

    private void clearUSerCache() {
        spUtil.save(ConstValue.Sp.SESSIONID, "");
        spUtil.save(ConstValue.Sp.PASSWORD, "");
        spUtil.save(ConstValue.Sp.COOKIE, "");
    }

    private DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            AppManager.finishAllActivity();
        }
    };

}

